<template>
  <div class="availability bg-white page-content content">
    <q-scroll-area ref="scrollTargetRef" class="full-height" :thumb-style="thumbStyle">
      <div class="row title-list" style="padding: 20px 10px 0">
        <div class="col-lg-6 col-md-6 col-sm-6 title-item" v-for="(item, index) in titleList" :key="index">
          <div class=" relative-position item">
            <div class="absolute" style="top: 10px;right:10px;" @click="detailNotice(index)" :class="{'link': index > 1}">
              <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" />
              <q-tooltip max-width="300px">{{item.tips}}</q-tooltip>
            </div>
            <div class="bg-l absolute"></div>
            <div class="bg-s absolute"></div>
              <div class="absolute icon-bg flex justify-center items-center">
                <q-icon class="iconfont" :class="item.icon"></q-icon>
              </div>
              <div class="absolute title-content">
                <div class="margin-b-10">{{item.value}}</div>
                <div class="font-16">{{item.label}}</div>
            </div>
          </div>
          <div class="flex new-title-item">
            <div v-for="(v, i) in dayShiftDetails" :key="i" class="flex-1 item relative-position" :class="index===0? 'count' : 'rate'">
                <div class="absolute" style="top: 10px;right:10px;" :class="{'link': index > 1}">
                  <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" />
                  <q-tooltip max-width="300px">{{index === 0 ? v.countTips : v.rateTips}}</q-tooltip>
                </div>
                <div class="bg-l absolute"></div>
                <div class="bg-s absolute"></div>
                <div class="absolute icon-bg flex justify-center items-center">
                  <q-icon class="iconfont" :class="index === 0 ? v.countIcon : v.rateIcon"></q-icon>
                </div>
                <div class="absolute title-content">
                  <div class="margin-b-10">{{ (index === 0 ? v.productCount : v.availabilityRate) || 0}}</div>
                  <div class="font-16 ellipsis">{{v.current ? '当班' : v.shiftName}}{{index === 0 ? '产量' : '时间开动率'}}</div>
                </div>
            </div>
          </div>
        </div>
      </div>
      <div class="font-size-16 text-center">
        当日开动率趋势图
        <span style="cursor: pointer" @click="actuationVisible=true">
          <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" />
          <q-tooltip max-width="300px">当日开动率=2小时内设备实际加工状态总时长/该时段开始时间到当前时间的计划工作总时长x100%</q-tooltip>
        </span>
      </div>
      <div style="height: 500px;width: calc(100% - 40px)" class="margin-r-20 margin-l-20" ref="availability"></div>
      <div class="font-size-16 text-center">
        当日产量分布图
        <span>
          <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" />
          <q-tooltip max-width="300px">当日2小时产量统计，柱状图表示所在整点时刻开始2小时内的产量</q-tooltip>
        </span>
      </div>
      <div style="height: 500px;width: calc(100% - 40px)" class="margin-r-20 margin-l-20" ref="output"></div>
    </q-scroll-area>

    <drawer
      title="说明"
      :visible.sync="actuationVisible"
      width="500px"
      close-on-click-modal>
      <div class="notice-detail">
        <div>1.当班产量：此刻所在轮班内该设备的产量汇总，若该车间未设置班制则当班产量为0</div>
        <div>2.当日产量：当班首日开始时刻起到当前时刻的设备产量汇总</div>
        <div>3.当班时间开动率：</div>
        <div class="notice-desc">a.当班开动率：当班设备加工状态总时长/当前班制开始时间到当前时间的计划工作总时长x100%；</div>
        <div class="notice-desc">b.根据当前时间变化持续更新</div>
        <div class="notice-desc">c.处于换班时间内，当班开动率为0.00%</div>
        <div class="notice-desc">d.若该车间未设置班制则当班时间开动率为0</div>
        <div>4.当日时间开动率：</div>
        <div class="notice-desc">a.当日开动率：当日设备加工状态总时长/当日第一个班制开始时间到当前时间的计划工作总时长x100%；</div>
        <div class="notice-desc">b.根据当前时间变化持续更新</div>
        <div>5.当日开动率趋势图：</div>
        <div class="notice-desc">a. 从班制开始时间绘制，每两个小时统计一次，数据全都落到前一个时间点（例如8:00-10:00,10:00-12:00，若在10:30产生循环，则数据落在10:00的节点上计算）</div>
        <div class="notice-desc">b.图内各点开动率=2小时内设备实际加工状态总时长/该时段开始时间到当前时间的计划工作总时长x100%；</div>
      </div>
    </drawer>
  </div>
</template>

<script>
import moment from 'moment'
import echarts from 'echarts'
import { getAvailability } from 'src/boot/status-monitor/machine'
import _ from 'lodash'
import { addListener } from 'resize-detector'
import Drawer from 'src/components/drawer/drawer.vue'

export default {
  name: 'availability',
  components: {
    Drawer
  },
  props: {
    id: {
      default: null
    }
  },
  data () {
    return {
      details: null,
      // 滚动条样式
      thumbStyle: this.CommonConfig.thumbStyle,
      date: moment(new Date()).format('YYYY-MM-DD'),
      availabilityChart: null,
      availabilityData: {},
      outputChart: null,
      outputData: {},
      dayShiftDetails: [],
      titleList: [
        // {
        //   label: '当班产量',
        //   value: 0,
        //   icon: 'icontubiao2-81',
        //   tips: '此刻所在轮班内该设备的产量汇总，若该车间未设置班制则当班产量为零'
        // },
        {
          label: '当日产量',
          value: 0,
          icon: 'icontubiao2-82',
          tips: '当班首日开始时刻起到当前时刻的设备产量汇总'
        },
        // {
        //   label: '当班时间开动率',
        //   value: '0.00%',
        //   icon: 'icontubiao2-83',
        //   tips: '当班设备加工状态总时长/当前班制开始时间到当前时间的计划工作总时长x100%'
        // },
        {
          label: '当日时间开动率',
          value: '0.00%',
          icon: 'icontubiao2-84',
          tips: '当日时间开动率=当日设备加工状态总时长/当日第一个班制开始时间到当前时间的计划工作总时长x100%'
        }
      ],
      actuationVisible: false
    }
  },
  mounted () {
    this.getData()
    // window.addEventListener('resize', () => {
    //   if (this.availabilityChart) {
    //     this.availabilityChart.resize()
    //   }
    //   if (this.outputChart) {
    //     this.outputChart.resize()
    //   }
    // })

    addListener(this.$refs.availability, this.$utils.debounce(() => {
      if (this.availabilityChart) {
        this.availabilityChart.resize()
      }
      if (this.outputChart) {
        this.outputChart.resize()
      }
    }, 100))
  },
  watch: {
    id (val) {
      this.getData()
    }
  },
  methods: {
    detailNotice (index) {
      if (index !== 1) return
      this.actuationVisible = true
    },
    // 当日开动率趋势
    getData () {
      getAvailability(this.id).then(res => {
        const data = res.data
        // const emptyData = {
        //   time: ['0:00', '2:00', '4:00', '6:00', '8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'],
        //   value: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        // }
        if (!_.isEmpty(data)) {
          this.dayShiftDetails = data.dayShiftDetails.map(v => {
            return {
              ...v,
              availabilityRate: (v.availabilityRate ? v.availabilityRate * 100 : 0).toFixed(2) + '%',
              rateIcon: 'icontubiao2-83',
              countIcon: 'icontubiao2-81',
              rateTips: v.current ? '当班设备加工状态总时长/当前班制开始时间到当前时间的计划工作总时长x100%' : '班制内的设备运行加工状态总时长/班制内计划工作总时长*100%',
              countTips: v.current ? '此刻所在轮班内该设备的产量汇总，若该车间未设置班制则当班产量为零' : '此班制开始时刻到结束时刻的产量汇总'
            }
          })
          console.log(this.dayShiftDetails)
          // this.titleList[0].value = (data.productCountShift).toLocaleString('en-US')
          this.titleList[0].value = (data.productCountDay).toLocaleString('en-US')
          // this.titleList[2].value = (data.availabilityRateShift ? data.availabilityRateShift * 100 : 0).toFixed(2) + '%'
          this.titleList[1].value = (data.availabilityRateDay ? data.availabilityRateDay * 100 : 0).toFixed(2) + '%'
          let outputData = {
            time: [],
            value: []
          }
          if (data.productCounts.length) {
            data.productCounts.forEach(item => {
              outputData.time.push(item.date)
              outputData.value.push(item.productCount)
            })
          }
          // else {
          //   outputData = emptyData
          // }

          this.outputData = outputData
          let availabilityData = {
            time: [],
            value: []
          }
          if (data.availabilityRates.length) {
            data.availabilityRates.forEach(item => {
              availabilityData.time.push(item.date)
              availabilityData.value.push((item.availabilityRate * 100).toFixed(2))
            })
          }
          // else {
          //   availabilityData = emptyData
          // }
          this.availabilityData = availabilityData
        }
      }).then(() => {
        this.getAvailabilityChart()
        this.getOutputChart()
      })
    },
    // 开动率图表渲染
    getAvailabilityChart () {
      if (this.availabilityChart) {
        this.availabilityChart.clear()
        // 绘制图表
        const option = this.getAvailabilityChartOption()
        this.availabilityChart.setOption(option)
      } else {
        // 基于准备好的dom，初始化echarts实例
        this.$nextTick(function () {
          this.availabilityChart = echarts.init(this.$refs.availability)
          // 绘制图表
          const option = this.getAvailabilityChartOption()
          this.availabilityChart.setOption(option)
        })
      }
    },
    // 产量图表渲染
    getOutputChart () {
      if (this.availabilityChart) {
        this.outputChart.clear()
        // 绘制图表
        const option = this.getOutputChartOption()
        this.outputChart.setOption(option)
      } else {
        // 基于准备好的dom，初始化echarts实例
        this.$nextTick(function () {
          this.outputChart = echarts.init(this.$refs.output)
          // 绘制图表
          const option = this.getOutputChartOption()
          this.outputChart.setOption(option)
        })
      }
    },
    // 开动率图标配置项
    getAvailabilityChartOption () {
      const date = moment(this.date).format('MM-DD')
      const options = {
        // title: {
        //   text: '当日开动率趋势图',
        //   left: 'center',
        //   textStyle: {
        //     fontSize: 16,
        //     fontWeight: '400'
        //   }
        // },
        legend: {
          data: ['时间开动率(A)'],
          left: 'right',
          top: 5
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              type: 'dashed'
            }
          },
          formatter: function (params, ticket, callback) {
            var htmlStr = ''
            var value = params[0].value
            htmlStr += '<div>'
            htmlStr += params[0].marker
            htmlStr += date + ' ' + params[0].name
            htmlStr += '<div style="padding-left: 15px;margin-top: 5px">'
            htmlStr += '开动率: ' + value + '%'
            htmlStr += '</div>'
            htmlStr += '</div>'
            return htmlStr
          }
        },
        grid: {
          left: 60,
          right: 20,
          top: 57,
          bottom: 40
        },
        xAxis: [{
          type: 'category',
          data: this.availabilityData.time,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisTick: {
            show: false
          }
        }],
        yAxis: [{
          type: 'value',
          name: '百分比',
          nameGap: 20,
          splitNumber: 4,
          nameTextStyle: {
            color: '#333333',
            align: 'right',
            lineHeight: 50,
            fontSize: 14
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisLabel: {
            formatter: function (val) {
              return val + '%'
            },
            fontSize: 14
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333'
            }
          },
          splitArea: {
            show: false
          }
        }],
        series: [{
          name: '时间开动率(A)',
          type: 'line',
          data: this.availabilityData.value,
          lineStyle: {
            normal: {
              width: 5,
              color: '#5F77FD',
              shadowColor: 'rgba(95, 119, 253, 0.3)',
              shadowBlur: 10,
              shadowOffsetY: 20
            }
          },
          symbolSize: 15,
          itemStyle: {
            normal: {
              color: '#5F77FD',
              borderWidth: 3,
              borderColor: '#5F77FD'
            },
            emphasis: {
              color: '#5F77FD',
              borderColor: '#5F77FD'
            }
          },
          smooth: true
        }]
      }
      return options
    },
    // 产量图表配置项
    getOutputChartOption () {
      const date = moment(this.date).format('MM-DD')
      const options = {
        // title: {
        //   text: '当日产量分布图',
        //   left: 'center',
        //   textStyle: {
        //     fontSize: 16,
        //     fontWeight: '400'
        //   }
        // },
        legend: {
          data: ['产量'],
          left: 'right',
          icon: 'circle',
          top: 5
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              type: 'dashed'
            }
          },
          formatter: function (params, ticket, callback) {
            let htmlStr = ''
            const color = `linear-gradient(#44D8C6, #5F77FD)`
            htmlStr += '<div>'
            htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-image:' + color + ';"></span>'
            htmlStr += date + ' ' + params[0].name
            htmlStr += '<div style="padding-left: 15px;margin-top: 5px">'
            htmlStr += '产量: ' + params[0].value
            htmlStr += '</div>'
            htmlStr += '</div>'
            return htmlStr
          }
        },
        grid: {
          left: 60,
          right: 20,
          top: 57,
          bottom: 40
        },
        xAxis: [{
          type: 'category',
          data: this.outputData.time,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisTick: {
            show: false
          }
        }],
        yAxis: [{
          type: 'value',
          name: '产量数',
          nameGap: 20,
          splitNumber: 4,
          nameTextStyle: {
            color: '#333333',
            align: 'right',
            lineHeight: 50,
            fontSize: 14
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisLabel: {
            fontSize: 14
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333'
            }
          },
          splitArea: {
            show: false
          }
        }],
        series: [{
          name: '产量',
          data: this.outputData.value,
          type: 'bar',
          barWidth: 16,
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: '#44D8C6'
              },
              {
                offset: 1,
                color: '#5F77FD'
              }]),
              barBorderRadius: [6, 6, 0, 0]
            }
          },
          label: {
            show: false
          }
        }]
      }
      return options
    }
  }
}
</script>

<style scoped lang="stylus">
  .link {
    cursor: pointer;
  }
  .notice-detail {
    .title{
      font-size 16px;
      font-weight bold;
      margin-bottom: 12px;
    }

    .notice-desc {
      margin-left 12px
    }

    .subtitle {
      font-weight bold;
    }

    .box-wrap{
      margin-top 12px;
    }
  }
  .title-item > .item{
    height 169px
    border-radius 6px
    margin 0 10px 20px
    box-shadow 0px 0px 7px 0px rgba(22,22,22,0.2)
  }
  .bg-l{
    height 64px
    width 64px
    opacity .1
    top 10px
    left 34px
    border-radius 50%
  }
  .bg-s{
    height 40px
    width 40px
    opacity .1
    top 34px
    left 10px
    border-radius 50%
  }
  .icon-bg{
    height 64px
    width 64px
    border-radius 50%
    top 53px
    right 40px
  }
  .title-list{
    .title-content{
      top 50px
      left 40px
      height calc(100% - 50px)
      width calc(100% - 80px)
      &>div:first-child{
        font-size 46px
        line-height 1
      }
      &>div:last-child{
        color #999999
        font-weight 500
      }
    }
    //.title-item:nth-child(1){
    //  & .bg-l,& .bg-s{
    //    background-color #F7B82D
    //  }
    //  & .icon-bg{
    //    background-color rgba(247, 184, 45, .2)
    //  }
    //  & .iconfont {
    //    font-size 24px
    //    color #F7B82D
    //    &.font-18{
    //      font-size 18px
    //    }
    //  }
    //}
    .title-item:nth-child(1){
      & .bg-l,& .bg-s{
        background-color #18D77F
      }
      & .icon-bg{
        background-color rgba(24, 215, 127, .2)
      }
      & .iconfont {
        font-size 24px
        color #18D77F
        &.font-18{
          font-size 18px
        }
      }
    }
    //.title-item:nth-child(3){
    //  & .bg-l,& .bg-s{
    //    background-color #5F77FD
    //  }
    //  & .icon-bg{
    //    background-color rgba(95, 119, 253, .2)
    //  }
    //  & .iconfont {
    //    font-size 24px
    //    color #5F77FD
    //    &.font-18{
    //      font-size 18px
    //    }
    //  }
    //}
    .title-item:nth-child(2){
      & .bg-l,& .bg-s{
        background-color #AF23CC
      }
      & .icon-bg{
        background-color rgba(175, 35, 204, .2)
      }
      & .iconfont {
        font-size 24px
        color #AF23CC
        &.font-18{
          font-size 18px
        }
      }
    }
    .new-title-item > .item{
      height 100px
      border-radius 6px
      margin 0 10px 20px
      box-shadow 0px 0px 7px 0px rgba(22,22,22,0.2)

      .bg-l{
        height 30px
        width 30px
        opacity .1
        top 5px
        left 20px
        border-radius 50%
      }
      .bg-s{
        height 20px
        width 20px
        opacity .1
        top 25px
        left 8px
        border-radius 50%
      }
      .icon-bg{
        height 25px
        width 25px
        border-radius 50%
        top 63px
        right 10px
      }
      .title-content{
        top 35px
        left 10px
        height calc(100% - 50px)
        width calc(100% - 40px)
        &>div:first-child{
          font-size 20px
        }
        &>div:last-child{
          color #999999
          font-size 14px
          font-weight 500
        }
      }
      .iconfont{
        font-size  16px !important
      }
    }
    .new-title-item{
      .count{
        & .bg-l,& .bg-s{
          background-color #F7B82D
        }
        & .icon-bg{
          background-color rgba(247, 184, 45, .2)
        }
        & .iconfont {
          font-size 24px
          color #F7B82D
          &.font-18{
            font-size 18px
          }
        }
      }
      .rate{
        & .bg-l,& .bg-s{
          background-color #5F77FD
        }
        & .icon-bg{
          background-color rgba(95, 119, 253, .2)
        }
        & .iconfont {
          font-size 24px
          color #5F77FD
          &.font-18{
            font-size 18px
          }
        }
      }
    }
  }
</style>
